package com.x.Part2_Comparator;

/**
 * ClassName: Phone
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.03.28 20:42
 */
public class Phone implements Comparable{
    String name;
    int price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public Phone() {
    }

    public Phone(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Phone{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    //指定在当前类中，按什么规则把对象排序
    @Override
    public int compareTo(Object o) {
        if(this == o)
            return 0;

        if(o instanceof Phone) {
            Phone p = (Phone) o;

//            if(p.price> this.price)
//                return 1;
//            else if (p.price == this.price)
//                return 0;
//            else
//                return -1;
            int tem = Integer.compare(this.price, p.price);
            if(tem != 0)
                return tem;
            else
                return this.name.compareTo(p.name);//若价格相同，比较商品名
        }
        //手动抛出异常
        throw new RuntimeException("类型不匹配");
    }
}
